<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="clearfix">
          <span>证书模板编辑</span>
          <el-button style="float: right;" type="primary" @click="goBack">返回</el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="templateInfo" label-width="100px" size="default">
            <el-form-item label="模板名称">
              <el-input v-model="templateInfo.name" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="模板类型">
              <el-input v-model="templateInfo.type" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="模板格式">
              <el-input v-model="templateInfo.templateFormat" :disabled="true"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      
      <el-divider content-position="center">模板内容与操作</el-divider>
      
      <!-- DOCX 模板操作 -->
      <div v-if="isDocxTemplate">
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="24">
            <el-alert
              title="DOCX模板管理"
              type="info"
              description="您可以下载当前的Word模板进行本地编辑，然后上传新版本以替换。系统将基于最新的Word模板进行PDF导出。"
              :closable="false"
              show-icon>
            </el-alert>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-button type="primary" icon="Download" @click="downloadDocxTemplate" :disabled="!templateInfo.templateFileUrl">下载当前模板</el-button>
          </el-col>
          <el-col :span="12">
            <el-upload
              ref="uploadDocx"
              :action="uploadDocxUrl"
              :headers="uploadHeaders"
              :data="{ templateId: templateId }"
              :before-upload="beforeDocxUpload"
              :on-success="handleDocxUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              :auto-upload="true"
              :show-file-list="true"
              name="file" 
            >
              <template #trigger>
                <el-button type="success" icon="Upload">上传替换模板</el-button>
              </template>
            </el-upload>
          </el-col>
           <el-col :span="6">
             <el-button type="warning" icon="View" @click="previewDocxTemplate" :disabled="!templateInfo.templateFileUrl">预览Word (HTML)</el-button>
           </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-button type="warning" @click="testDownloadSample" style="margin-left:10px;">测试下载样例</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- HTML/RichText 模板操作 -->
      <div v-if="!isDocxTemplate">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="editor-toolbar">
            <el-button-group>
              <el-button type="primary" @click="saveContent">保存</el-button>
              <el-button type="success" @click="previewContent">预览</el-button>
              <el-button type="info" @click="resetContent">重置</el-button>
            </el-button-group>
            
            <el-radio-group v-model="editorType" style="margin-left: 20px;" @change="handleEditorTypeChange">
              <el-radio-button label="rich">富文本编辑</el-radio-button>
              <el-radio-button label="html">HTML编辑</el-radio-button>
            </el-radio-group>
          </div>
          
          <!-- 富文本编辑器 -->
          <div v-if="editorType === 'rich'" class="rich-editor-container" v-loading="loading">
            <div v-if="!isTinyMCELoaded" class="editor-loading">
              加载编辑器中...
            </div>
            <div id="richTextEditor" class="tinymce-editor"></div>
          </div>
          
          <!-- HTML代码编辑器 -->
          <div v-if="editorType === 'html'" class="html-editor-container" v-loading="loading">
            <el-input
              type="textarea"
              v-model="editorContent"
              :disabled="loading"
              :rows="20"
              class="html-editor"
            ></el-input>
          </div>
          </el-col>
        </el-row>
      </div>
      
      <el-divider content-position="center">通用操作</el-divider>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-button type="warning" icon="View" @click="openExportDialog">导出为PDF</el-button>
        </el-col>
      </el-row>
      
      <el-divider content-position="center">变量列表</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-table :data="variableList" size="default" border style="width: 100%">
            <el-table-column prop="name" label="变量名" width="180"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="defaultValue" label="默认值" width="180"></el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="insertVariable(scope.row.name)"
                >插入</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 预览对话框 -->
    <el-dialog title="模板预览" v-model="previewVisible" width="60%">
      <div class="preview-container" v-loading="previewLoading">
        <div v-html="previewHtml"></div>
      </div>
    </el-dialog>
    
    <!-- 导出PDF对话框 -->
    <el-dialog title="导出PDF" v-model="exportVisible" width="50%">
      <div v-loading="exportLoading">
        <el-alert
          title="请填写模板变量值，系统将根据这些值生成PDF文件"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        ></el-alert>
        
        <el-form :model="exportForm" label-width="100px">
          <el-form-item 
            v-for="variable in variableList" 
            :key="variable.name" 
            :label="variable.description || variable.name">
            <el-input 
              v-model="exportForm[variable.name]" 
              :placeholder="variable.defaultValue || '请输入' + variable.name">
            </el-input>
          </el-form-item>
        </el-form>
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
          <el-button @click="exportVisible = false">取消</el-button>
          <el-button type="primary" @click="exportToPdf" :loading="exportLoading">导出PDF</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getTemplate, 
  updateTemplate, 
  previewTemplate, 
  listTemplateVariables,
  exportToPdf,
  parseWord,
  downloadTemplateFile
} from "@/api/qep/certificate/template"
import { getToken } from "@/utils/auth"
import { ElMessage, ElNotification, ElMessageBox, ElLoading } from 'element-plus'

export default {
  name: "TemplateEditor",
  components: {},
  data() {
    return {
      // 模板ID
      templateId: null,
      // 模板信息
      templateInfo: {
        id: null,
        name: '',
        type: '',
        templateFormat: 'HTML',
        editorType: 'rich',
        templateFileUrl: ''
      },
      // 编辑器内容
      editorContent: '',
      // 编辑器类型 (rich: 富文本, html: HTML)
      editorType: 'rich',
      // 原始内容
      originalContent: '',
      // 加载状态
      loading: false,
      // 预览相关
      previewVisible: false,
      previewHtml: '',  // 改名为previewHtml避免与方法名冲突
      previewLoading: false,
      // 变量列表
      variableList: [],
      // 富文本编辑器配置
      richEditorInit: {
        height: 500,
        language: 'zh_CN',
        menubar: 'file edit view insert format tools table help',
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount',
          'wordpaster importwordtoimg netpaster wordimport excelimport pptimport pdfimport',
          'zycapture zyoffice'
        ],
        toolbar:
          'undo redo | formatselect | bold italic backcolor | ' +
          'alignleft aligncenter alignright alignjustify | ' +
          'bullist numlist outdent indent | removeformat | ' + 
          'wordpaster importwordtoimg netpaster wordimport excelimport pptimport pdfimport zycapture zyoffice | ' +
          'help',
        branding: false,
        // 配置图片上传
        images_upload_url: '/api/qep/file/upload/image',
        automatic_uploads: true,
        images_reuse_filename: false,
        // 自定义图片上传处理函数
        images_upload_handler: function (blobInfo, success, failure, progress) {
          const formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());
          
          const xhr = new XMLHttpRequest();
          xhr.open('POST', '/api/qep/file/upload/image');
          
          xhr.onload = function() {
            if (xhr.status !== 200) {
              failure('HTTP Error: ' + xhr.status);
              return;
            }
            
            try {
              const json = JSON.parse(xhr.responseText);
              if (json && json.code === 200 && json.data && json.data.url) {
                success(json.data.url);
              } else {
                failure('Invalid JSON response: ' + xhr.responseText);
              }
            } catch (e) {
              failure('Invalid JSON: ' + xhr.responseText);
            }
          };
          
          xhr.onerror = function () {
            failure('Image upload failed');
          };
          
          if (xhr.upload && progress) {
            xhr.upload.onprogress = function (e) {
              progress(e.loaded / e.total * 100);
            };
          }
          
          xhr.send(formData);
        }
      },
      // WordPaster相关配置
      edtData: "<p>泽优Word一键粘贴控件（WordPaster） for vue3-cli-tinymce5</p><p>泽优全平台Word一键粘贴控件（WordPaster）</p><p>泽优全平台截屏控件（zyCapture）</p><p>泽优Office文档转换服务（zyOffice）</p>",
      initConfig: {
        selector: 'textarea',
        skin: 'oxide',
        valid_elements: 'p[*],h1[*],h2[*],span[*],strong/b,img[*],table[*]',
        custom_elements: '~h1>div,~h1>strong,~h1>span,~h1>table,~span>span,~h2>strong',
        valid_children: '+h1[div|table|span|svg],+h2[span]',
        fix_list_elements: false,
        validate: false,
        inline_styles: true,
        convert_fonts_to_spans: false,
        paste_retain_style_properties: 'all',
        paste_filter_drop: false,
        allow_html_in_named_anchor: true,
        branding: false,
        elementpath: false,
        menubar: false,
        statusbar: false,
        external_plugins: {
          zycapture: window.location.origin + '/zyCapture/plugin.min.js',
          wordpaster: window.location.origin + '/WordPaster/plugin/wordpaster.js',
          importwordtoimg: window.location.origin + '/WordPaster/plugin/importwordtoimg.js',
          netpaster: window.location.origin + '/WordPaster/plugin/netpaster.js',
          wordimport: window.location.origin + '/WordPaster/plugin/wordimport.js',
          excelimport: window.location.origin + '/WordPaster/plugin/excelimport.js',
          pptimport: window.location.origin + '/WordPaster/plugin/pptimport.js',
          pdfimport: window.location.origin + '/WordPaster/plugin/pdfimport.js',
          zyoffice: window.location.origin + '/zyOffice/plugin/zyoffice.js',
          zywordexport: window.location.origin + '/zyOffice/plugin/zywordexport.js',
          zyofficepdf: window.location.origin + '/zyOffice/plugin/zyofficepdf.js'
        },
        plugins: 'autoresize',
        toolbar: 'bold italic underline forecolor fontselect fontsizeselect | alignleft aligncenter ' +
          'alignright alignjustify | bullist numlist outdent indent | ' +
          'removeformat | cut | wordimport excelimport pptimport pdfimport | ' +
          'importwordtoimg netpaster zycapture | zyoffice',
        height: 200,
        paste_data_images: true,
        width: '100%'
      },
      // 导出PDF相关
      exportVisible: false,
      exportLoading: false,
      exportForm: {},
      isTinyMCELoaded: false,
      uploadHeaders: { Authorization: "Bearer " + getToken() },
    };
  },
  computed: {
    isDocxTemplate() {
      return this.templateInfo && this.templateInfo.templateFormat === 'DOCX';
    },
    uploadDocxUrl() {
      return `/api/qep/certificate/template/replace-docx?templateId=${this.templateId}`;
    }
  },
  created() {
    // 从路由获取模板ID
    this.templateId = this.$route.query.id;
    if (this.templateId) {
      this.getTemplateInfo();
      this.getVariableList();
    } else {
      ElMessage.error("未指定模板ID");
      this.goBack();
    }
  },
  
  mounted() {
    // 检查TinyMCE是否已加载
    this.checkTinyMCE();
    
    // 初始化插件
    this.initPlugins();
    
    // 延迟一点初始化编辑器，确保DOM已更新
    this.$nextTick(() => {
      if (this.editorType === 'rich') {
        this.switchToRichEditor();
      }
    });

    // 添加图标修复函数
    this.setupIconFixer();
  },
  methods: {
    // 检查TinyMCE是否已加载
    checkTinyMCE() {
      if (window.tinymce) {
        console.log('TinyMCE已加载');
        this.isTinyMCELoaded = true;
        
        // 安全地注册插件
        if (!window.tinymce.PluginManager.get('paste')) {
          window.tinymce.PluginManager.add('paste', function(editor) {
            return {};
          });
        }
        
        if (!window.tinymce.PluginManager.get('print')) {
          window.tinymce.PluginManager.add('print', function(editor) {
            return {};
          });
        }
      } else {
        console.log('TinyMCE未加载，尝试动态加载');
        // 如果CDN链接加载失败，可以尝试动态加载本地文件
        const script = document.createElement('script');
        script.src = '/tinymce/tinymce.min.js';
        script.onload = () => {
          console.log('TinyMCE动态加载成功');
          this.isTinyMCELoaded = true;
          
          // 注册插件
          window.tinymce.PluginManager.add('paste', function(editor) {
            return {};
          });
          
          window.tinymce.PluginManager.add('print', function(editor) {
            return {};
          });
        };
        script.onerror = (err) => {
          console.error('TinyMCE加载失败，尝试从CDN加载:', err);
          const cdnScript = document.createElement('script');
          cdnScript.src = 'https://cdn.jsdelivr.net/npm/tinymce@6.7.0/tinymce.min.js';
          cdnScript.onload = () => {
            console.log('TinyMCE从CDN加载成功');
            this.isTinyMCELoaded = true;
            
            // 注册插件
            window.tinymce.PluginManager.add('paste', function(editor) {
              return {};
            });
            
            window.tinymce.PluginManager.add('print', function(editor) {
              return {};
            });
          };
          cdnScript.onerror = () => {
            console.error('TinyMCE加载失败，请刷新页面重试');
            ElMessage.error('编辑器加载失败，请刷新页面重试');
          };
          document.head.appendChild(cdnScript);
        };
        document.head.appendChild(script);
      }
    },
    
    // 初始化所有插件
    initPlugins() {
      try {
        // 确保TinyMCE已加载
        if (window.tinymce) {
          // 动态加载基础插件脚本
          const loadPluginScripts = () => {
            return new Promise((resolve, reject) => {
              // 加载的插件脚本计数
              let loadedCount = 0;
              const requiredScripts = 3; // w.js, z.js (zyCapture), z.js (zyOffice)
              
              // 加载WordPaster插件
              const wordpasterScript = document.createElement('script');
              wordpasterScript.src = window.location.origin + '/WordPaster/js/w.js';
              wordpasterScript.onload = () => {
                console.log('WordPaster JS文件加载成功');
                loadedCount++;
                if (loadedCount === requiredScripts) resolve();
              };
              wordpasterScript.onerror = (err) => {
                console.error('WordPaster加载失败:', err);
                reject(err);
              };
              document.head.appendChild(wordpasterScript);
              
              // 加载zyCapture插件
              const zyCaptureScript = document.createElement('script');
              zyCaptureScript.src = window.location.origin + '/zyCapture/z.js';
              zyCaptureScript.onload = () => {
                console.log('zyCapture JS文件加载成功');
                loadedCount++;
                if (loadedCount === requiredScripts) resolve();
              };
              zyCaptureScript.onerror = (err) => {
                console.error('zyCapture加载失败:', err);
                reject(err);
              };
              document.head.appendChild(zyCaptureScript);
              
              // 加载zyOffice插件
              const zyOfficeScript = document.createElement('script');
              zyOfficeScript.src = window.location.origin + '/zyOffice/js/z.js';
              zyOfficeScript.onload = () => {
                console.log('zyOffice JS文件加载成功');
                loadedCount++;
                if (loadedCount === requiredScripts) resolve();
              };
              zyOfficeScript.onerror = (err) => {
                console.error('zyOffice加载失败:', err);
                reject(err);
              };
              document.head.appendChild(zyOfficeScript);
            });
          };
          
          // 加载插件脚本，然后初始化
          loadPluginScripts().then(() => {
            // 初始化WordPaster
            if (window.WordPaster) {
              this.initWordPaster();
            }
            
            // 初始化zyOffice
            if (window.zyOffice) {
              window.zyOffice.getInstance({
                word: '/api/qep/certificate/template/parse-word',
                wordExport: '/api/qep/certificate/template/export-word',
                pdf: '/api/qep/certificate/template/parse-pdf'
              });
            }
            
            // 初始化zyCapture
            if (window.zyCapture) {
              window.zyCapture.getInstance({
                config: {
                  PostUrl: '/api/qep/file/upload/image',
                  License2: '',
                  FileFieldName: 'file',
                  Fields: { uname: 'test' },
                  ImageUrl: '{url}'
                }
              });
            }
          }).catch(err => {
            console.error('插件脚本加载失败:', err);
          });
        } else {
          console.error('TinyMCE未加载，无法初始化插件');
        }
      } catch (err) {
        console.error('初始化插件出错:', err);
      }
    },
    
    // 初始化WordPaster
    initWordPaster() {
      try {
        // 检查window对象上是否有WordPaster
        if (window.WordPaster) {
          console.log('WordPaster plugin found');
          // 初始化WordPaster
          window.WordPaster.getInstance({
            // 上传接口
            PostUrl: '/api/qep/file/wordpaster/upload',
            // 为图片地址增加域名
            ImageUrl: '{url}',
            // 设置文件字段名称
            FileFieldName: 'file',
            // 提取图片地址
            ImageMatch: ''  
          });
        }
      } catch (err) {
        console.error('初始化WordPaster插件出错:', err);
      }
    },
    
    // 获取模板信息
    getTemplateInfo() {
      this.loading = true;
      getTemplate(this.templateId).then(response => {
        this.templateInfo = response.data;
        if (!this.isDocxTemplate) {
        this.editorContent = this.templateInfo.editorContent || this.templateInfo.content || '';
        this.originalContent = this.editorContent;
        this.editorType = this.templateInfo.editorType || 'rich';
        } else {
          this.editorContent = '';
          this.originalContent = '';
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        ElMessage.error("获取模板信息失败");
      });
    },
    
    // 获取变量列表
    getVariableList() {
      listTemplateVariables(this.templateId).then(response => {
        console.log('获取变量列表成功:', response);
        if (response && response.data) {
          this.variableList = response.data || [];
          // 初始化导出表单
          this.initExportForm();
        } else {
          console.warn('变量列表返回数据为空');
          this.variableList = [];
          this.initExportForm();
        }
      }).catch((error) => {
        console.error('获取变量列表失败:', error);
        ElMessage.error("获取变量列表失败: " + (error.message || '未知错误'));
        // 使用空数组初始化
        this.variableList = [];
        this.initExportForm();
      });
    },
    
    // 初始化导出表单
    initExportForm() {
      this.exportForm = {};
      if (this.variableList && this.variableList.length > 0) {
      this.variableList.forEach(variable => {
          this.exportForm[variable.name] = variable.defaultValue || '';
      });
      }
    },
    
    // 保存内容
    saveContent() {
      if (this.isDocxTemplate) {
        ElMessage.info("DOCX模板请通过\"上传替换模板\"按钮更新。");
        return;
      }
      this.loading = true;
      const dataToSave = {
        ...this.templateInfo,
        editorContent: this.editorContent,
        editorType: this.editorType
      };
      
      updateTemplate(dataToSave).then(() => {
        this.loading = false;
        this.originalContent = this.editorContent;
        ElMessage.success("模板内容保存成功");
      }).catch(() => {
        this.loading = false;
        ElMessage.error("保存失败");
      });
    },
    
    // 预览内容
    async previewContent() {
      if (this.isDocxTemplate) {
         this.previewDocxTemplate();
         return;
      }
      this.previewLoading = true;
      this.previewVisible = true;
      try {
        const response = await previewTemplate(this.templateId, { content: this.editorContent });
        if (typeof response === 'string') {
          this.previewHtml = response;
        } else if (response && response.data && typeof response.data === 'string') {
          this.previewHtml = response.data;
          } else {
          this.previewHtml = '<p>无法获取预览内容。</p>';
        }
      } catch (error) {
        console.error("预览失败:", error);
        this.previewHtml = '<p>预览加载失败。</p>';
        ElMessage.error("预览失败: " + (error.message || "未知错误"));
      } finally {
        this.previewLoading = false;
      }
    },
    
    // 重置内容
    resetContent() {
      if (this.isDocxTemplate) {
        ElMessage.info("DOCX模板无法在此重置。");
        return;
      }
      this.$confirm('确定要重置为原始内容吗？未保存的修改将丢失。').then(() => {
        this.editorContent = this.originalContent;
        if (this.editorType === 'rich' && window.tinymce && window.tinymce.get('richTextEditor')) {
          window.tinymce.get('richTextEditor').setContent(this.editorContent);
        }
      }).catch(() => {});
      ElMessage.success("内容已重置为上次保存的状态");
    },
    
    // 切换编辑器类型
    handleEditorTypeChange(type) {
      if (type === 'rich') {
        this.switchToRichEditor();
      } else {
        // 从富文本切换到HTML模式
        if (window.tinymce && window.tinymce.get('richTextEditor')) {
          // 如果富文本编辑器存在，先获取其内容
          const editor = window.tinymce.get('richTextEditor');
          this.editorContent = editor.getContent();
          // 销毁富文本编辑器实例
          editor.destroy();
        }
        this.editorType = type;
      }
    },
    
    // 插入变量
    insertVariable(varName) {
      const variableText = '${' + varName + '}';
      
      if (this.editorType === 'html') {
        // 对于HTML编辑器，直接在光标位置插入
        const textarea = document.querySelector('.html-editor textarea');
        if (textarea) {
          const start = textarea.selectionStart;
          const end = textarea.selectionEnd;
          this.editorContent = 
            this.editorContent.substring(0, start) + 
            variableText + 
            this.editorContent.substring(end);
        } else {
          // 如果无法访问textarea元素，则追加到末尾
          this.editorContent += variableText;
        }
      } else {
        // 对于富文本编辑器，使用TinyMCE API插入
        const editor = window.tinymce?.get('richTextEditor');
        if (editor) {
          editor.execCommand('mceInsertContent', false, variableText);
        } else {
          console.warn('富文本编辑器未初始化，无法插入变量');
          // 直接更新内容
          this.editorContent += variableText;
        }
      }
      
      ElMessage.success(`已插入变量${varName}`);
    },
    
    // 打开导出对话框
    openExportDialog() {
      this.initExportForm();
      this.exportVisible = true;
    },
    
    // 导出为PDF
    exportToPdf() {
      if (!this.templateId) {
        ElMessage.error("模板ID不能为空");
        return;
      }
      
      this.exportLoading = true;
      
      // 添加超时处理
      const timeoutPromise = new Promise((_, reject) => 
        setTimeout(() => reject(new Error('请求超时，请稍后再试')), 30000)
      );
      
      // 合并请求和超时
      Promise.race([
        exportToPdf(this.templateId, this.exportForm),
        timeoutPromise
      ])
        .then(response => {
          this.exportLoading = false;
          this.exportVisible = false;
          
          const blob = new Blob([response], { type: 'application/pdf' });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = `${this.templateInfo.name || 'certificate'}_preview.pdf`;
          link.click();
          URL.revokeObjectURL(link.href);
          
          ElNotification({
            title: '导出成功',
            message: '证书已成功导出为PDF文件',
            type: 'success'
          });
        })
        .catch(error => {
          this.exportLoading = false;
          console.error("导出PDF失败:", error);
          
          // 如果是DOCX模板，提供下载链接作为备选
          if (this.isDocxTemplate && this.templateInfo.templateFileUrl) {
            ElMessageBox.confirm(
              '导出PDF失败。您可以下载原始Word文档并在本地转换为PDF。是否下载原文档？',
              '导出失败',
              {
                confirmButtonText: '下载Word文档',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              this.downloadDocxTemplate();
            }).catch(() => {});
          }
          
          ElMessage.error(`导出失败: ${error.message || '未知错误'}`);
        });
    },
    
    // 返回
    goBack() {
      this.$router.push('/certificate/template');
    },

    // 处理编辑器内容变更
    handleEditorChange(content) {
      this.editorContent = content;
    },

    // 切换到富文本编辑器
    switchToRichEditor() {
      this.loading = true;
      this.editorType = 'rich';
      
      // 确保TinyMCE已加载
      if (!window.tinymce) {
        console.log('TinyMCE未加载，尝试动态加载');
        this.checkTinyMCE();
      }
      
      // 加载自定义图标
      this.loadIcons();
      
      // 确保插件已加载
      const loadPlugins = new Promise((resolve) => {
        // 检查插件是否已加载
        if (window.WordPaster && window.zyOffice && window.zyCapture) {
          resolve();
          return;
        }
        
        // 初始化插件
        this.initPlugins();
        
        // 插件加载可能需要一点时间
        setTimeout(resolve, 1000);
      });
      
      loadPlugins.then(() => {
        // 等待主DOM更新后再初始化编辑器
        this.$nextTick(() => {
          // 确保编辑器容器已清空
          const editorContainer = document.getElementById('richTextEditor');
          if (editorContainer) {
            editorContainer.innerHTML = '';
            
            // 初始化TinyMCE
            window.tinymce.init({
              selector: '#richTextEditor',
              height: 500,
              language: 'zh_CN',
              language_url: window.location.origin + '/tinymce/langs/zh_CN.js',
              content_css: window.location.origin + '/tinymce/icons/custom/custom-icons.css',
              menubar: 'file edit view insert format tools table help',
              plugins: [
                'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'print', 'preview', 'anchor',
                'searchreplace', 'visualblocks', 'code', 'fullscreen', 'cut',
                'insertdatetime', 'media', 'table', 'paste', 'code', 'help', 'wordcount',
                'zycapture', 'zyoffice'
              ],
              external_plugins: {
                zycapture: window.location.origin + '/zyCapture/plugin.min.js',
                wordpaster: window.location.origin + '/WordPaster/plugin/wordpaster.js',
                importwordtoimg: window.location.origin + '/WordPaster/plugin/importwordtoimg.js',
                netpaster: window.location.origin + '/WordPaster/plugin/netpaster.js',
                wordimport: window.location.origin + '/WordPaster/plugin/wordimport.js',
                excelimport: window.location.origin + '/WordPaster/plugin/excelimport.js',
                pptimport: window.location.origin + '/WordPaster/plugin/pptimport.js',
                pdfimport: window.location.origin + '/WordPaster/plugin/pdfimport.js',
                zyoffice: window.location.origin + '/zyOffice/plugin/zyoffice.js',
                zywordexport: window.location.origin + '/zyOffice/plugin/zywordexport.js',
                zyofficepdf: window.location.origin + '/zyOffice/plugin/zyofficepdf.js',
                cut: window.location.origin + '/tinymce/plugins/cut/plugin.min.js',
                newdocument: window.location.origin + '/tinymce/plugins/newdocument/plugin.min.js'
              },
              toolbar: 'newdocument undo redo | formatselect | ' +
                'bold italic backcolor | alignleft aligncenter ' +
                'alignright alignjustify | bullist numlist outdent indent | ' +
                'removeformat | cut | wordimport excelimport pptimport pdfimport | ' +
                'importwordtoimg netpaster zycapture | zyoffice',
              // 配置图片上传
              images_upload_url: '/api/qep/file/upload/image',
              automatic_uploads: true,
              images_reuse_filename: false,
              // 自定义图片上传处理函数
              images_upload_handler: (blobInfo, progress) => {
                return new Promise((resolve, reject) => {
                  const xhr = new XMLHttpRequest();
                  xhr.withCredentials = false;
                  xhr.open('POST', '/api/qep/file/upload/image');
                  
                  xhr.upload.onprogress = (e) => {
                    progress(e.loaded / e.total * 100);
                  };
                  
                  xhr.onload = () => {
                    if (xhr.status < 200 || xhr.status >= 300) {
                      reject('HTTP Error: ' + xhr.status);
                      return;
                    }
                    
                    try {
                      const json = JSON.parse(xhr.responseText);
                      if (!json || json.code !== 200 || !json.data || !json.data.url) {
                        reject('无效的JSON响应: ' + xhr.responseText);
                        return;
                      }
                      
                      resolve(json.data.url);
                    } catch (e) {
                      reject('无效的JSON: ' + xhr.responseText);
                    }
                  };
                  
                  xhr.onerror = () => {
                    reject('图片上传失败');
                  };
                  
                  const formData = new FormData();
                  formData.append('file', blobInfo.blob(), blobInfo.filename());
                  xhr.send(formData);
                });
              },
              // 文档导入处理函数
              wordimport_handler: (file, success, failure) => {
                try {
                  // 使用我们的API方法代替原生XHR
                  parseWord(file).then(response => {
                    if (response && response.code === 200 && response.data) {
                      success(response.data);
                    } else {
                      failure('解析失败: ' + (response.msg || '未知错误'));
                    }
                  }).catch(error => {
                    console.error('Word导入处理函数错误:', error);
                    failure('导入处理错误: ' + (error.message || '服务器错误'));
                  });
                } catch (error) {
                  console.error('Word导入处理函数错误:', error);
                  failure('导入处理错误: ' + error.message);
                }
              },
              excelimport_handler: (file, success, failure) => {
                try {
                  const formData = new FormData();
                  formData.append('file', file);
                  
                  const xhr = new XMLHttpRequest();
                  xhr.open('POST', '/api/qep/certificate/template/parse-excel');
                  xhr.withCredentials = true;
                  
                  xhr.onload = () => {
                    if (xhr.status < 200 || xhr.status >= 300) {
                      failure('HTTP Error: ' + xhr.status);
                      return;
                    }
                    
                    try {
                      const response = JSON.parse(xhr.responseText);
                      if (response && response.code === 200 && response.data) {
                        success(response.data);
                      } else {
                        failure('解析失败: ' + (response.msg || '未知错误'));
                      }
                    } catch (e) {
                      failure('无效的JSON: ' + xhr.responseText);
                    }
                  };
                  
                  xhr.onerror = () => {
                    failure('上传文件出错');
                  };
                  
                  xhr.send(formData);
                } catch (error) {
                  console.error('Excel导入处理函数错误:', error);
                  failure('导入处理错误: ' + error.message);
                }
              },
              pptimport_handler: (file, success, failure) => {
                try {
                  const formData = new FormData();
                  formData.append('file', file);
                  
                  const xhr = new XMLHttpRequest();
                  xhr.open('POST', '/api/qep/certificate/template/parse-ppt');
                  xhr.withCredentials = true;
                  
                  xhr.onload = () => {
                    if (xhr.status < 200 || xhr.status >= 300) {
                      failure('HTTP Error: ' + xhr.status);
                      return;
                    }
                    
                    try {
                      const response = JSON.parse(xhr.responseText);
                      if (response && response.code === 200 && response.data) {
                        success(response.data);
                      } else {
                        failure('解析失败: ' + (response.msg || '未知错误'));
                      }
                    } catch (e) {
                      failure('无效的JSON: ' + xhr.responseText);
                    }
                  };
                  
                  xhr.onerror = () => {
                    failure('上传文件出错');
                  };
                  
                  xhr.send(formData);
                } catch (error) {
                  console.error('PowerPoint导入处理函数错误:', error);
                  failure('导入处理错误: ' + error.message);
                }
              },
              pdfimport_handler: (file, success, failure) => {
                try {
                  const formData = new FormData();
                  formData.append('file', file);
                  
                  const xhr = new XMLHttpRequest();
                  xhr.open('POST', '/api/qep/certificate/template/parse-pdf');
                  xhr.withCredentials = true;
                  
                  xhr.onload = () => {
                    if (xhr.status < 200 || xhr.status >= 300) {
                      failure('HTTP Error: ' + xhr.status);
                      return;
                    }
                    
                    try {
                      const response = JSON.parse(xhr.responseText);
                      if (response && response.code === 200 && response.data) {
                        success(response.data);
                      } else {
                        failure('解析失败: ' + (response.msg || '未知错误'));
                      }
                    } catch (e) {
                      failure('无效的JSON: ' + xhr.responseText);
                    }
                  };
                  
                  xhr.onerror = () => {
                    failure('上传文件出错');
                  };
                  
                  xhr.send(formData);
                } catch (error) {
                  console.error('PDF导入处理函数错误:', error);
                  failure('导入处理错误: ' + error.message);
                }
              },
              // Word导入配置
              wordimport_service_url: '/api/qep/certificate/template/parse-word',
              // Excel导入配置
              excelimport_service_url: '/api/qep/certificate/template/parse-excel',
              // PPT导入配置
              pptimport_service_url: '/api/qep/certificate/template/parse-ppt',
              // PDF导入配置
              pdfimport_service_url: '/api/qep/certificate/template/parse-pdf',
              setup: (editor) => {
                const _this = this;
                // 添加自定义图标
                editor.on('init', function() {
                  console.log('编辑器初始化完成，自定义图标已加载');
                  
                  // 设置初始内容
                  editor.setContent(_this.editorContent || '');
                  
                  // 编辑器加载完成
                  _this.loading = false;
                  _this.isTinyMCELoaded = true;
                });
                
                // 监听内容变化
                editor.on('change', function() {
                  _this.editorContent = editor.getContent();
                });
                
                // 监听导入完成事件
                editor.on('WordImportComplete', function(e) {
                  ElMessage.success('Word文档导入成功');
                });
                
                editor.on('ExcelImportComplete', function(e) {
                  ElMessage.success('Excel文档导入成功');
                });
                
                editor.on('PptImportComplete', function(e) {
                  ElMessage.success('PowerPoint文档导入成功');
                });
                
                editor.on('PdfImportComplete', function(e) {
                  ElMessage.success('PDF文档导入成功');
                });
                
                // 添加导入完成后的错误处理
                editor.on('ImportError', function(e) {
                  ElMessage.error('导入失败: ' + e.message);
                });
                
                // 修复图标显示
                setTimeout(() => {
                  _this.fixTinyMCEIcons();
                }, 1000);
              },
            }).catch((error) => {
              console.error('TinyMCE初始化失败:', error);
              this.loading = false;
            });
          } else {
            console.error('找不到富文本编辑器容器');
            this.loading = false;
          }
        });
      }).catch((err) => {
        console.error('加载插件失败:', err);
        this.loading = false;
      });
    },

    // 设置图标修复器
    setupIconFixer() {
      // 定时检查和修复图标显示问题
      setTimeout(() => {
        this.fixTinyMCEIcons();
      }, 3000);
    },

    // 修复TinyMCE图标问题
    fixTinyMCEIcons() {
      console.log('尝试修复TinyMCE图标');
      try {
        // 查找所有TinyMCE按钮
        const buttons = document.querySelectorAll('.tox-tbtn');
        buttons.forEach(btn => {
          const ariaLabel = btn.getAttribute('aria-label');
          if (!ariaLabel) return;
          
          // 对特定的按钮进行处理
          if (['Word粘贴', 'Word转图片', '网络图片', '导入Excel', '导入PPT', '导入PDF', '截图', 'Office文档'].includes(ariaLabel)) {
            // 查找图标容器
            const iconContainer = btn.querySelector('.tox-icon');
            if (!iconContainer) return;
            
            // 查找SVG元素并隐藏
            const svg = iconContainer.querySelector('svg');
            if (svg) {
              svg.style.display = 'none';
            }
            
            // 查找图片元素，如果不存在则添加
            let img = iconContainer.querySelector('img');
            if (!img) {
              img = document.createElement('img');
              img.style.width = '20px';
              img.style.height = '20px';
              img.style.verticalAlign = 'middle';
              
              // 根据按钮类型设置正确的图片路径
              let imgPath = '';
              switch(ariaLabel) {
                case 'Word粘贴':
                  imgPath = '/WordPaster/plugin/word1.png';
                  break;
                case 'Word转图片':
                  imgPath = '/WordPaster/plugin/word2.png';
                  break;
                case '网络图片':
                  imgPath = '/WordPaster/plugin/net.png';
                  break;
                case '导入Excel':
                  imgPath = '/WordPaster/plugin/excel.png';
                  break;
                case '导入PPT':
                  imgPath = '/WordPaster/plugin/ppt.png';
                  break;
                case '导入PDF':
                  imgPath = '/WordPaster/plugin/pdf.png';
                  break;
                case '截图':
                  imgPath = '/zyCapture/z.png';
                  break;
                case 'Office文档':
                  imgPath = '/zyOffice/plugin/w.png';
                  break;
              }
              
              img.src = window.location.origin + imgPath;
              iconContainer.appendChild(img);
            }
          }
        });
      } catch (err) {
        console.error('修复图标时出错:', err);
      }
    },

    // 尝试将界面翻译为中文
    translateEditorUI() {
      console.log('尝试将界面翻译为中文');
      try {
        // 翻译菜单项
        const translateMenuItems = () => {
          const menuItems = {
            'File': '文件',
            'Edit': '编辑',
            'View': '视图',
            'Insert': '插入',
            'Format': '格式',
            'Table': '表格',
            'Tools': '工具',
            'Help': '帮助'
          };

          // 查找所有菜单项
          document.querySelectorAll('.tox-mbtn__select-label').forEach(element => {
            const text = element.textContent;
            if (menuItems[text]) {
              element.textContent = menuItems[text];
            }
          });

          // 查找下拉菜单项
          document.querySelectorAll('.tox-collection__item-label').forEach(element => {
            const text = element.textContent;
            Object.keys(menuItems).forEach(key => {
              if (text && text.includes(key)) {
                element.textContent = text.replace(key, menuItems[key]);
              }
            });
          });
        };

        // 翻译按钮提示
        const translateButtonTooltips = () => {
          const tooltips = {
            'Bold': '粗体',
            'Italic': '斜体',
            'Underline': '下划线',
            'Strikethrough': '删除线',
            'Align left': '左对齐',
            'Align center': '居中',
            'Align right': '右对齐',
            'Justify': '两端对齐',
            'Bullet list': '项目符号列表',
            'Numbered list': '编号列表',
            'Decrease indent': '减少缩进',
            'Increase indent': '增加缩进'
          };

          // 遍历所有按钮
          document.querySelectorAll('.tox-tbtn').forEach(btn => {
            const ariaLabel = btn.getAttribute('aria-label');
            if (tooltips[ariaLabel]) {
              btn.setAttribute('aria-label', tooltips[ariaLabel]);
              btn.setAttribute('title', tooltips[ariaLabel]);
            }
          });
        };

        // 执行翻译
        translateMenuItems();
        translateButtonTooltips();

        // 确保我们的自定义插件按钮图标正确显示
        this.fixTinyMCEIcons();
      } catch (err) {
        console.error('翻译界面时出错:', err);
      }
    },

    // 加载自定义图标
    loadIcons() {
      const iconsScript = document.createElement('script');
      iconsScript.src = window.location.origin + '/tinymce/icons/custom/icons.js';
      iconsScript.onload = () => {
        console.log('自定义图标脚本加载成功');
      };
      iconsScript.onerror = (err) => {
        console.error('自定义图标脚本加载失败:', err);
      };
      document.head.appendChild(iconsScript);
      
      // 加载自定义CSS
      const customIconsLink = document.createElement('link');
      customIconsLink.rel = 'stylesheet';
      customIconsLink.href = window.location.origin + '/tinymce/icons/custom/custom-icons.css';
      document.head.appendChild(customIconsLink);
    },

    // --- DOCX模板特定方法 ---
    downloadDocxTemplate() {
      if (!this.templateInfo || !this.templateId) {
        ElMessage.error("模板信息不完整，无法下载");
        return;
      }
      
      // 显示加载提示
      const loading = ElLoading.service({
        text: '正在准备下载...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 尝试直接从API下载
      downloadTemplateFile(this.templateId)
        .then(response => {
          loading.close();
          
          // 创建Blob对象
          const blob = new Blob([response], { 
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
          });
          
          // 检查内容是否有效
          if (blob.size === 0) {
            throw new Error("下载的文件内容为空");
          }
          
          console.log("下载的文件大小:", blob.size, "字节");
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          
          // 生成文件名
          const fileName = `${this.templateInfo.name || 'template'}_${this.templateId}.docx`;
          link.download = fileName;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          
          // 清理
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
          
          ElMessage.success("文件下载成功");
        })
        .catch(error => {
          loading.close();
          console.error("下载文件失败:", error);
          
          // 获取文件直接从存储路径下载
          const directDownloadUrl = this.getDirectDownloadUrl();
          if (directDownloadUrl) {
            ElMessageBox.confirm(
              '从API下载失败，是否尝试直接从文件服务器下载？',
              '下载失败',
              {
                confirmButtonText: '尝试直接下载',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              console.log("尝试从URL直接下载:", directDownloadUrl);
              
              // 保存组件的this引用
              const self = this;
              const templateName = this.templateInfo.name || 'template';
              
              // 创建一个XMLHttpRequest来获取文件
              const xhr = new XMLHttpRequest();
              xhr.open('GET', directDownloadUrl, true);
              xhr.responseType = 'blob';
              
              // 添加加载提示
              const directLoading = ElLoading.service({
                text: '尝试直接下载...',
                background: 'rgba(0, 0, 0, 0.7)'
              });
              
              xhr.onload = function() {
                directLoading.close();
                
                if (this.status === 200) {
                  const blob = new Blob([this.response], { 
                    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
                  });
                  
                  // 检查内容是否有效
                  if (blob.size === 0) {
                    ElMessage.error("下载的文件内容为空，请联系管理员");
                    return;
                  }
                  
                  console.log("直接下载的文件大小:", blob.size, "字节");
                  
                  // 创建下载链接
                  const link = document.createElement('a');
                  link.href = URL.createObjectURL(blob);
                  
                  // 使用之前保存的templateName
                  const fileName = `${templateName}_direct.docx`;
                  link.download = fileName;
                  
                  // 触发下载
                  document.body.appendChild(link);
                  link.click();
                  
                  // 清理
                  window.URL.revokeObjectURL(link.href);
                  document.body.removeChild(link);
                  
                  ElMessage.success("文件直接下载成功");
                } else {
                  ElMessage.error(`直接下载失败: 服务器返回 ${this.status} 错误`);
                }
              };
              
              xhr.onerror = function() {
                directLoading.close();
                ElMessage.error("网络错误，无法直接下载文件");
              };
              
              xhr.send();
            }).catch(() => {
              // 用户取消，不执行操作
            });
          } else {
            ElMessage.error("下载文件失败，无法获取有效的下载链接");
          }
        });
    },
    
    // 获取直接下载URL
    getDirectDownloadUrl() {
      if (!this.templateInfo || !this.templateInfo.templateFileUrl) {
        return null;
      }
      
      let templateUrl = this.templateInfo.templateFileUrl;
      
      // 检查URL格式
      if (templateUrl.startsWith('http')) {
        // 已经是完整URL
        return templateUrl;
      }
      
      // 处理不同的URL格式
      let baseUrl = window.location.origin;
      
      // 移除可能的开头斜杠
      if (templateUrl.startsWith('/')) {
        templateUrl = templateUrl.substring(1);
      }
      
      // 尝试不同的URL路径格式
      const possibleUrls = [
        `${baseUrl}/profile/${templateUrl}`,
        `${baseUrl}/${templateUrl}`,
        `${baseUrl}/profile/certificate_templates/${templateUrl.split('/').pop()}`,
        `${baseUrl}/certificate_templates/${templateUrl.split('/').pop()}`
      ];
      
      console.log("可能的URL:", possibleUrls);
      
      // 返回第一个URL，前端会尝试它
      return possibleUrls[0];
    },

    beforeDocxUpload(file) {
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.name.endsWith('.docx');
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isDocx) {
        ElMessage.error('上传文件只能是 DOCX 格式!');
      }
      if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!');
      }
      return isDocx && isLt10M;
    },

    handleDocxUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        ElMessage.success('新模板上传成功');
        if (response.data && response.data.templateFileUrl) {
          this.templateInfo.templateFileUrl = response.data.templateFileUrl;
        }
         if (response.data && response.data.version) {
          this.templateInfo.version = response.data.version;
        }
        this.getTemplateInfo();
        this.$refs.uploadDocx.clearFiles();
      } else {
        ElMessage.error('模板上传失败: ' + (response.msg || '未知错误'));
      }
    },

    handleUploadError(err, file, fileList) {
      try {
        const errorResponse = JSON.parse(err.message);
        ElMessage.error('上传失败: ' + (errorResponse.msg || errorResponse.message || '服务内部错误'));
      } catch (e) {
        // 处理不同类型的错误
        if (err.status === 500) {
          ElMessage.error('服务器内部错误，请联系管理员。可能的原因：文件权限问题、存储空间不足或服务配置错误');
        } else if (err.status === 404) {
          ElMessage.error('上传接口不存在，请确认后端服务已启动');
        } else if (err.status === 401 || err.status === 403) {
          ElMessage.error('没有权限上传文件，请检查您的账号权限');
        } else {
          ElMessage.error('上传失败，请检查网络连接或联系管理员。原始错误: ' + (err.message || '未知错误'));
        }
        console.error('文件上传错误详情:', err);
      }
    },
    async previewDocxTemplate() {
      if (!this.templateId) {
        ElMessage.error("无法预览，模板ID缺失");
        return;
      }
      this.previewLoading = true;
      this.previewVisible = true;
      
      try {
        // 检查是否有模板文件URL
        if (!this.templateInfo.templateFileUrl) {
          this.previewHtml = '<p>模板文件URL不存在，无法预览。</p>';
          this.previewLoading = false;
          return;
        }
        
        // 获取完整文件URL
        const fileUrl = this.getFileFullUrl(this.templateInfo.templateFileUrl);
        
        // 直接提供下载选项
        const fileName = this.templateInfo.name || 'document';
        this.previewHtml = `
          <div style="padding: 20px; text-align: center;">
            <h3>${fileName}</h3>
            <p>Word文档无法在浏览器中直接预览。请点击下方按钮下载文档进行查看。</p>
            <p><a href="${fileUrl}" download="${fileName}.docx" class="el-button el-button--primary" style="display: inline-block; padding: 8px 16px; background-color: #409eff; color: white; text-decoration: none; border-radius: 4px; margin: 10px 0;">
              <span style="margin-right: 5px;">⬇</span> 下载DOCX文件
            </a></p>
          </div>
        `;
      } catch (error) {
        console.error("DOCX预览失败:", error);
        this.previewHtml = `
          <div style="padding: 20px; text-align: center; color: #f56c6c;">
            <h3>预览失败</h3>
            <p>无法处理此Word文档。请尝试直接下载文档进行查看。</p>
            <p><button onclick="window.parent.downloadTemplateDocument()" class="el-button el-button--primary" style="display: inline-block; padding: 8px 16px; background-color: #409eff; color: white; border: none; border-radius: 4px; margin: 10px 0; cursor: pointer;">
              <span style="margin-right: 5px;">⬇</span> 下载DOCX文件
            </button></p>
            <small style="color: #909399;">${error.message || '处理错误'}</small>
          </div>
        `;
        
        // 在window对象上添加下载函数供iframe调用
        window.downloadTemplateDocument = this.downloadDocxTemplate;
        
        ElMessage.error("预览失败: " + (error.message || "未知错误"));
      } finally {
        this.previewLoading = false;
      }
    },

    // 获取文件URL的统一方法
    getFileFullUrl(fileUrl) {
      if (!fileUrl) return '';
      
      // 如果已经是完整URL，直接返回
      if (fileUrl.startsWith('http')) {
        return fileUrl;
      }
      
      // 根据不同的路径格式构建完整URL
      if (fileUrl.startsWith('/')) {
        // 根路径开始的相对路径
        return window.location.origin + fileUrl;
      } else if (fileUrl.includes('certificate_templates')) {
        // 证书模板目录
        return window.location.origin + '/profile/' + fileUrl;
      } else {
        // 其他情况，假设是模板目录下的文件
        return window.location.origin + '/profile/certificate_templates/' + fileUrl;
      }
    },

    // 测试下载样例文件
    testDownloadSample() {
      const loading = ElLoading.service({
        text: '正在测试下载...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 拼接测试文件URL
      const baseUrl = import.meta.env.VITE_APP_BASE_API || '';
      const testUrl = `${baseUrl}/qep/certificate/template/test-file/test_file`;
      
      console.log("测试下载URL:", testUrl);
      
      // 使用Fetch API直接下载
      fetch(testUrl)
        .then(response => {
          loading.close();
          
          if (!response.ok) {
            // 尝试从响应体获取更详细的错误信息
            return response.text().then(text => {
              throw new Error(`服务器响应错误: ${response.status} ${response.statusText}${text ? ' - ' + text : ''}`);
            });
          }
          
          return response.blob();
        })
        .then(blob => {
          console.log("获取到测试文件，大小: ", blob.size, "字节", "类型: ", blob.type);
          
          if (blob.size === 0) {
            throw new Error("下载的文件内容为空");
          }
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = "test_sample.txt";
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          
          // 清理
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
          
          ElMessage.success("测试文件下载成功，如果内容正确，说明服务器文件访问配置正常");
        })
        .catch(error => {
          loading.close();
          console.error("测试下载失败:", error);
          
          // 显示更友好的错误消息并提供更详细的诊断步骤
          ElMessageBox.alert(
            `<p><strong>测试下载失败:</strong> ${error.message || '未知错误'}</p>
            <p><strong>可能原因:</strong></p>
            <ol>
              <li>文件路径配置错误 - 检查 RuoYiConfig.getProfile() 返回的路径</li>
              <li>文件权限问题 - 检查目录权限是否允许应用程序读取</li>
              <li>服务器存储空间不足</li>
              <li>服务器未正确启动 - 检查日志输出</li>
            </ol>
            <p><strong>诊断步骤:</strong></p>
            <ol>
              <li>检查服务器日志获取详细错误信息</li>
              <li>验证文件目录 D:\\ruoyi\\uploadPath\\certificate_templates 是否存在</li>
              <li>尝试重启应用服务器</li>
            </ol>`,
            '下载测试失败',
            {
              confirmButtonText: '确定',
              type: 'error',
              dangerouslyUseHTMLString: true
            }
          );
        });
    },
  }
};
</script>

<style scoped>
.editor-toolbar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.rich-editor-container, .html-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}
.editor-loading {
  text-align: center;
  padding: 20px;
  color: #909399;
}
.preview-container {
  min-height: 300px;
  border: 1px solid #eee;
  padding: 10px;
  overflow: auto;
}
/* 确保上传组件的按钮样式正确 */
.el-upload {
  display: inline-block;
  margin-left: 10px;
}
</style> 